package com.example.ccj.b.c.custom.image;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;


import com.example.ccj.R;
import com.example.ccj.b.c.custom.TitleBarOnDisplayControl;
import com.example.ccj.b.c.custom.adapter.AdpterForRecyclerImagesLoadAndRemoveButton;
import com.example.ccj.b.c.dialog.SureOrCancelDialog;
import com.example.ccj.b.c.dialogxy.impl.DialogShowBigPicture;
import com.example.ccj.b.c.recycler.BaseRecycler;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.ScreenUtils;
import com.example.ccj.u.SizeUtils;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.UiUtils;
import com.example.ccj.u.media.IPictureSelectResultListener2;
import com.example.ccj.u.media.MediaUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 图片列表
 * 2022年9月16日17:02:44
 * 2022年10月21日21:50:42
 * 2024年12月26日15点22分
 *
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/12/26 15:23
 */
public class LoadImagesRecycler extends LinearLayout implements  AdpterForRecyclerImagesLoadAndRemoveButton.OnItemClickListener, AdpterForRecyclerImagesLoadAndRemoveButton.OnItemDeleteListener {
    private TitleBarOnDisplayControl title;                     //头view
    private BaseRecycler<MLocalMedia> rec;                      //加载图片的recycler
    public List<MLocalMedia> allImages;                         //所有图片
    private List<MLocalMedia> deleteImages;                     //删除的图片
    private List<MLocalMedia> addImages;                        //新添加的图片
    private int maxSum = 10;                                     //最大选择数量 默认10
    private String titleName = "图片";                            //名称
    private boolean isCanDelete = true;                         //是否可以删除
    private boolean isMastShoot = false;                        //是否必须拍照
    public static final int LOCAL = 0;                          //加载模式：本地数据 可随意添加
    public static final int NETWORK = 1;                        //加载模式：网络图片 不可添加删除
    public static final int NETWORK_AND_LOCAL_UPLOAD = 2;       //加载模式：初始数据为网络数据，后期可添加本地数据，上传网络完毕后回调才能添加进来
    public static final int NETWORK_AND_LOCAL_NO_UPLOAD = 3;    //加载模式：初始数据为网络数据，后期可添加本地数据，先添加后期再通过调用添加的数据进行上传
    private int loadMode = LOCAL;                               //加载模式  默认为加载本地图片模式
    private AdpterForRecyclerImagesLoadAndRemoveButton adapter; //adapter
    private ImageChangeListener imageChangeListener;          //图片更改事件


    public LoadImagesRecycler(Context context) {
        super(context);
        init();
    }

    public LoadImagesRecycler(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.LoadImagesRecycler);

        String title_text = t.getString(R.styleable.LoadImagesRecycler_title_text);
        String title_tag_text = t.getString(R.styleable.LoadImagesRecycler_title_tag_text);
        float title_text_size = t.getDimension(R.styleable.LoadImagesRecycler_title_text_size,SizeUtils.px2sp(15));
        float title_tag_text_size = t.getDimension(R.styleable.LoadImagesRecycler_title_tag_text_size,SizeUtils.px2sp(12));
        int title_text_color = t.getColor(R.styleable.LoadImagesRecycler_title_text_color, Color.parseColor("#2F365F"));
        int title_tag_text_color = t.getColor(R.styleable.LoadImagesRecycler_title_tag_text_color, Color.parseColor("#E91E63"));
        int title_src = t.getResourceId(R.styleable.LoadImagesRecycler_title_src, R.mipmap.def_img_select);
        int click_interval = t.getInt(R.styleable.LoadImagesRecycler_click_interval, 300);
        boolean click_only_one = t.getBoolean(R.styleable.LoadImagesRecycler_click_only_one, false);
        isCanDelete = t.getBoolean(R.styleable.LoadImagesRecycler_is_can_delete, true);
        maxSum = t.getInt(R.styleable.LoadImagesRecycler_max_sum, 10);
        loadMode = t.getInt(R.styleable.LoadImagesRecycler_pick_mode, 0);
        boolean titleVisible = t.getBoolean(R.styleable.LoadImagesRecycler_tile_visible,true); //是否显示头


        init();

        if (titleVisible) {
            title.setVisibility(VISIBLE);
            title.setTitle(title_text);
            title.setTag(title_tag_text);
            title.getTvTitleView().setTextSize(SizeUtils.px2sp(title_text_size));
            title.getTvTagView().setTextSize(SizeUtils.px2sp(title_tag_text_size));
            title.getTvTitleView().setTextColor(title_text_color);
            title.getTvTagView().setTextColor(title_tag_text_color);
            title.getImgRightView().setImageResource(title_src);
            title.getImgRightView().setCheckInterval(click_interval);
            title.getImgRightView().setOnlyOne(click_only_one);
        } else title.setVisibility(GONE);

        t.recycle();
    }

    public LoadImagesRecycler(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        LayoutInflater.from(getContext()).inflate(R.layout.custom_display_load_image, this);
        allImages = new ArrayList<>();
        deleteImages = new ArrayList<>();
        addImages = new ArrayList<>();

        title = findViewById(R.id.custom_display_load_image_title);
        rec = findViewById(R.id.custom_display_load_iamge_rec);
        //设置布局方式

        int appScreenWidth = ScreenUtils.getAppScreenWidth();
        int dpWidth = SizeUtils.px2dp(appScreenWidth);
        int i = dpWidth / 60;

        GridLayoutManager layoutManager = new GridLayoutManager(getContext(),i);
        rec.setLayoutManager(layoutManager);
    }

    /**
     * 设置加载模式
     *  LOCAL : 本地图片
     *  NETWORK ： 网络图片
     *  NETWORK_AND_LOCAL_UPLOAD ： 网络和可以添加本地 先上传后更新
     *  NETWORK_AND_LOCAL_NO_UPLOAD ：  网络和可以添加本地 先更新后上传
     */
    public LoadImagesRecycler setMode(int loadMode){
        this.loadMode = loadMode;
        isCanDelete = loadMode != NETWORK;
        return this;
    }

    /**
     * 设置名称
     * @param titleName 名称
     * @return 1
     */
    public LoadImagesRecycler setTitleName(String titleName){
        this.titleName = titleName;
        return this;
    }

    /**
     * 最大选择数量
     * @param maxSum 数量
     * @return 1
     */
    public LoadImagesRecycler setMaxSum(int maxSum){
        this.maxSum = maxSum;
        return this;
    }

    /**
     * 设置原始要显示的数据
     * @param mLocalMediaList 图片数据
     * @return 1
     */
    public LoadImagesRecycler setData(List<MLocalMedia> mLocalMediaList){
        if (mLocalMediaList != null) {
            this.allImages.clear();
            this.allImages.addAll(mLocalMediaList);
        }
        return this;
    }

    public LoadImagesRecycler setImageChangeListener(ImageChangeListener imageChangeListener){
        this.imageChangeListener = imageChangeListener;
        return this;
    }

    /**
     * 显示
     */
    public void show(){
        title.setTitle(titleName);

        if (isCanDelete) {
            title.getImgRightView().setVisibility(VISIBLE);
            title.setImageOnclick(v -> {
                MediaUtils mediaUtils = new MediaUtils();
                //是否必须拍照
                if (allImages.size() >= maxSum) {
                    ToastUtils.showShort("最多选择" + maxSum);
                    return;}
                if (isMastShoot) mediaUtils.camera(getContext(), (IPictureSelectResultListener2) myImages -> addImageFunction(myImages));
                else mediaUtils.pickMultiplePictureOrCamera(getContext(), new ArrayList<>(allImages), maxSum, (IPictureSelectResultListener2) myImages -> addImageFunction(myImages));
            });
            title.getImgRightView().setImageResource(R.mipmap.def_img_select);
        }
        title.showDashLine();

        adapter = new AdpterForRecyclerImagesLoadAndRemoveButton(getContext(), allImages,isCanDelete,this,this);
        rec.setAdapter(allImages,adapter);
        LogUtils.d("allImages" + allImages.hashCode());
    }

    /**
     * 替换图片
     * @param imagesArrayList 图片列表
     */
    @SuppressLint("NotifyDataSetChanged")
    public void replaceImage(ArrayList<MLocalMedia> imagesArrayList){
        this.allImages.clear();
        this.allImages.addAll(imagesArrayList);
        this.addImages.clear();
        rec.replaceData(imagesArrayList);
    }

    /**
     * 图片点击回调
     * @param po  当前的编号
     */
    @Override
    public void onItemsClick(int po) {
        DialogShowBigPicture dialogShowBigPicture = new DialogShowBigPicture(getContext());
        dialogShowBigPicture.setTitle(titleName);
        dialogShowBigPicture.setData(allImages)
                            .setImageChangeListener(ShowBigPictureControl.SHOW_MODEL_ONLY_SHOW)
                            .setImageChangeListener(new ShowBigImageChangeListener() {
                                @Override
                                public void imageDelete(MLocalMedia localMedia,int position) {
                                    delete3(localMedia);
                                }

                                @Override
                                public void over(ShowBigPictureControl control) {

                                }
                            });
        dialogShowBigPicture.show();
    }


    private void delete(MLocalMedia localMedia){
        rec.removeData(localMedia);
    }

    /**
     * 设置进度条
     * 当进度为100时隐藏
     * @param progress 进度最大100
     */
    public void setProgress(int progress){
        if (this.title.getProgressView().getVisibility() == GONE) this.title.getProgressView().setVisibility(VISIBLE);
        this.title.getProgressView().setProgress(progress);
        if (progress>=100) this.title.getProgressView().setVisibility(GONE);
    }

    /**
     * 设置提示文本
     * @param tag 提示
     */
    public LoadImagesRecycler setTag(String tag){
        this.title.setTag(tag);
        return this;
    }

    /**
     * 设置是否必须拍照
     * @param isMastShoot 等待
     */
    public LoadImagesRecycler setMastShoot(boolean isMastShoot){
        this.isMastShoot = isMastShoot;
        return this;
    }

    private void addImageFunction(List<MLocalMedia> myImages){
        List<MLocalMedia> nowAddImages = new ArrayList<>();

        for (MLocalMedia myImage : myImages) {
            if (!allImages.contains(myImage)) {
                nowAddImages.add(myImage);
            }
        }

        LogUtils.d("共加载" + nowAddImages.size());

        //上传完毕后再将图片加载进来
        if (!nowAddImages.isEmpty()) {
            if (loadMode == NETWORK_AND_LOCAL_UPLOAD) {
                if (imageChangeListener != null) {
                    imageChangeListener.imageInsertNetWork(nowAddImages, new IImageChangeUpload() {
                        //这里回传的应该是网络图片
                        @Override
                        public void onUpload(List<MLocalMedia> nowImages2) {
                            LogUtils.d("回调加载" + nowImages2.size());
                            rec.addDatas(nowImages2);
                            LogUtils.d("allimages的数量：" + allImages.size());
                        }
                    });
                }
            }

            //先加载进来再回调回去处理
            if (loadMode == NETWORK_AND_LOCAL_NO_UPLOAD || loadMode == LOCAL) {
                rec.addDatas(nowAddImages);
                LogUtils.d("添加" + nowAddImages.size());
                if (imageChangeListener != null) imageChangeListener.imageInsert(nowAddImages);
            }
        }
    }

    @Override
    public void onItemsClick(List<MLocalMedia> myImages, MLocalMedia deleteImage) {
        delete3(deleteImage);
    }


    private void delete3(MLocalMedia deleteImage){
        if (deleteImage.imageType == 1){
            //网络图片删除确认
            SureOrCancelDialog sureOrCancelDialog = new SureOrCancelDialog(getContext());
            sureOrCancelDialog.setCenterText( "确定删除这张图片吗？" + deleteImage.name);
            sureOrCancelDialog.setButtonSureText("确定").setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //回调删除方法删除
                    if (loadMode == NETWORK_AND_LOCAL_UPLOAD) {
                        if (imageChangeListener != null) {
                            imageChangeListener.imageNetWorkDelete(deleteImage, new IImageChangeDelete() {
                                @Override
                                public void onDelete(MLocalMedia deleteImage) {
                                    delete(deleteImage);
                                }
                            });
                        }
                    }

                    //先加载进来再回调回去处理
                    if (loadMode == NETWORK_AND_LOCAL_NO_UPLOAD || loadMode == LOCAL) {
                        delete(deleteImage);
                        if (imageChangeListener != null) {
                            imageChangeListener.imageLocalDelete(deleteImages);
                        }
                    }
                    deleteImages.add(deleteImage);

                }
            });
        }
        if (deleteImage.imageType == 0) {
            delete(deleteImage);
            if (imageChangeListener != null) {
                imageChangeListener.imageLocalDelete(deleteImages);
            }
        }
    }


    public TitleBarOnDisplayControl getTitleView() {
        return title;
    }

    public BaseRecycler<MLocalMedia> getRecView() {
        return rec;
    }

    public List<MLocalMedia> getAllImages() {
        return allImages;
    }

    public List<MLocalMedia> getDeleteImages() {
        return deleteImages;
    }

    public List<MLocalMedia> getAddImages() {
        return addImages;
    }

    public int getMaxSum() {
        return maxSum;
    }

    public String getTitleName() {
        return titleName;
    }

    public AdpterForRecyclerImagesLoadAndRemoveButton getAdapterView() {
        return adapter;
    }

    public ImageChangeListener getImageChangeListener() {
        return imageChangeListener;
    }

    public int getLoadMode() {
        return loadMode;
    }

    public boolean isCanDelete() {
        return isCanDelete;
    }

    public boolean isMastShoot() {
        return isMastShoot;
    }

}

